package com.lagou.edu.filter;

import com.lagou.edu.fegin.IUserServiceClient;
import com.lagou.edu.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @author 赵虎
 * @date 2021/2/23 1:00 上午
 */
@Slf4j
@Component
public class AuthorizeFilter extends ResponseUtil implements GlobalFilter, Ordered {

    @Autowired
    private IUserServiceClient userServiceClient;

    @Value("${api.exclude}")
    private String[] excludePaths;

    @Value("${config.response.message.unauthorize}")
    private String unauthorizeText;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    protected Mono<Void> responseStatusAndMessage(ServerHttpResponse response, HttpStatus httpStatus, String message) {
        byte[] datas = message.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        response.setStatusCode(httpStatus);
        response.getHeaders()
                .add("Content-Type", "text/html;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        for (String exclude : excludePaths) {
            if (antPathMatcher.match(exclude, path)) {
                return chain.filter(exchange);
            }
        }


        List<String> cookies = request.getHeaders().get("lagou-token");

        if (CollectionUtils.isEmpty(cookies)) {
            log.info("====>>>> request path: " + path + " need authorize,accessToken is null ===> result is fail!");
            return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
        }
        String token = cookies.get(0);
        String email = userServiceClient.getEmailByToken(token);
        if (Objects.isNull(email)) {
            log.info("====>>>> request path: " + path + " need authorize, result is fail!");
            return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
        }

        log.info("====>>>> request path: " + path + " need authorize, result is pass!");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
